package com.gexin.controller.xapp.user;


import cn.jpush.api.report.UsersResult;
import com.gexin.common.cache.CacheUtils;
import com.gexin.common.model.ApiResponse;
import com.gexin.common.utils.MessageUtils;
import com.gexin.common.utils.MoSmsUtils;
import com.gexin.common.utils.OtherUtil;
import com.gexin.common.utils.StringUtil;
import com.gexin.core.interceptor.XAppSafeInterceptor;
import com.gexin.core.web.AppController;
import com.gexin.core.web.XAppController;
import com.gexin.model.activity.Coupon;
import com.gexin.model.activity.MemberInfo;
import com.gexin.model.agent.Agent;
import com.gexin.model.agent.AgentCity;
import com.gexin.model.integral.UserIntegralRecord;
import com.gexin.model.notice.NoticeNewsComment;
import com.gexin.model.notice.NoticeNewsCommentReply;
import com.gexin.model.order.Order;
import com.gexin.model.product.Products;
import com.gexin.model.user.Feedback;
import com.gexin.model.user.UserCoupon;
import com.gexin.model.user.UserRebate;
import com.gexin.model.weixin.UserAddress;
import com.gexin.model.weixin.WeixinUser;
import com.gexin.service.conpon.CouponService;
import com.gexin.service.conpon.UserCouponService;
import com.gexin.service.notice.NoticeNewsService;
import com.gexin.service.user.UserService;
import com.gexin.weixin.kit.WeiXinRedisKey;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 个人中心首页
 */
@Before(XAppSafeInterceptor.class)//统一错误拦截
@ControllerBind(controllerKey = "/xapp/user")
public class UserCenterController extends AppController {

	public void index(){
		WeixinUser weixinUser = getAuthUser();
		if(weixinUser!=null){
			String s = getAuthUserId() + "";
 			MemberInfo memberInfoByUserId = MemberInfo.dao.getMemberInfoByUserId(s);
			if(memberInfoByUserId==null){
				memberInfoByUserId = new MemberInfo();
//				memberInfoByUserId.setMemberInfo(System.currentTimeMillis()/1000+"",weixinUser.getId()+"",0);
			}
			weixinUser.put("memberId",memberInfoByUserId.getUserId());

//			Agent agent = Agent.dao.findInfoByUserIdAndStatus(weixinUser.getId(),Agent.STATUS_SUCCESS);
			Agent agent = Agent.dao.findInfoByUserIdALL(weixinUser.getId());
			weixinUser.put("agent",agent);
			if(agent!=null){
				if(Agent.TYPE_AREA.equals(agent.getType())){
					Long orderSize = Order.dao.findAreaAgentSize(agent.getId());
					weixinUser.put("orderSize",orderSize);
				}else{
					Long orderSize = Order.dao.findAgentSize(agent.getId());
					weixinUser.put("orderSize",orderSize);
				}
				List<AgentCity> agentList = AgentCity.dao.findByAgentId(agent.getId(),AgentCity.STATUS_SUCCESS);
				agent.put("agentList",agentList);
//				Long orderSize = Order.dao.findAgentSize(agent.getId());
//				weixinUser.put("orderSize",orderSize);
				Long productSize = Products.dao.findAgentSize(agent.getId());
				weixinUser.put("productSize",productSize);
			}
			weixinUser.put("await_pay_count", Db.queryLong("select count(id) from t_order where user_id = ? and state = 0 and type = 1 ",weixinUser.getId()));
			weixinUser.put("await_ship_count", Db.queryLong("select count(id) from t_order where user_id = ? and state = 1 and type = 1 ",weixinUser.getId()));
			weixinUser.put("already_ship_count", Db.queryLong("select count(id) from t_order where user_id = ? and state = 2 and type = 1 ",weixinUser.getId()));
			weixinUser.put("refund_count", Db.queryLong("select count(id) from t_order where user_id = ? and state = 6  and type = 1 ",weixinUser.getId()));
			//预售
			weixinUser.put("presale_count", Db.queryLong("select count(id) from t_order where user_id = ? and state in (0,1,2,6)  and type = 2 ",weixinUser.getId()));
		}
		renderJson(weixinUser);
	}

	/**
	 * 保存收货地址
	 */
	public void saveAddress(){
		UserAddress address = getModel(UserAddress.class , "address");
		ApiResponse apiResponse = UserService.dao.saveAddress(address , getAuthUser());
		renderJson(apiResponse);
	}

	public void findUserAddress(){
		List<UserAddress> list = UserService.dao.findUserAddressListByUserId(getAuthUser().getId());
		renderJson(list);
	}

	/**
	 * 获取地址详情
	 */
	public void addressInfo(){
		String addressId = getPara("address_id");
		if(StringUtil.isBlank(addressId)){
			fail("地址id不能为null!");
			return;
		}
		UserAddress userAddress = UserService.dao.findUserAddressInfoById(addressId);
		success(userAddress);
	}

	/**
	 * 删除收货地址
	 */
	public void delete(){
		String addressId = getPara("address_id");
		if(StringUtil.isBlank(addressId)){
			fail("地址id不存在!");
			return;
		}

		ApiResponse apiResponse = UserService.dao.deleteUserAddressById(addressId);
		renderJson(apiResponse);
	}


	/**
	 * 用户签到
	 */
	public void checkIn(){
		WeixinUser authUser = getAuthUser();
		if(authUser==null){
			fail("用户未登录!");
			return;
		}
		ApiResponse apiResponse = UserService.dao.singIn(authUser);
		renderJson(apiResponse);
	}

	/**
	 * 获取所有我的评论
	 */
	public void myComment(){
		WeixinUser authUser = getAuthUser();
		if (authUser==null){
			fail("用户未登录!");
			return;
		}
		List<NoticeNewsComment> comments = UserService.dao.myComment(authUser);
		renderJson(comments);
	}

	/**
	 * 给评论点赞
	 */
	public void commentZan(){
		String commentId = getPara("comment_id");
		if(StringUtil.isBlank(commentId)){
			fail("评论id不能为null!");
			return;
		}
		WeixinUser user = WeixinUser.dao.findById(getAuthUserId());
		ApiResponse apiResponse = UserService.dao.commentZan(commentId , user);
		renderJson(apiResponse);
	}

	/**
	 * 给资讯点赞
	 * /xapp/user/noticeZan  notice_id
	 */
	public void noticeZan(){
		String noticeId = getPara("notice_id");
		if(StringUtil.isBlank(noticeId)){
			fail("资讯id不能为null!");
			return;
		}
		WeixinUser user = getAuthUser();
		ApiResponse apiResponse = UserService.dao.noticeZan(noticeId , user);
		renderJson(apiResponse);
	}


	/**
	 * 获取优惠券列表
	 * /xapp/user/couponList   page  size
	 */
	public void couponList(){
		Page<Coupon> page = CouponService.dao.findList(getPageIndex() , getPageSize());
		renderJson(page);
	}


	/**
	 * 领取优惠券
	 * /xapp/user/receiveCoupon coupon_id
	 */
	public void receiveCoupon(){
		String couponId = getPara("coupon_id");
		WeixinUser authUser = getAuthUser();
		if(StringUtil.isBlank(couponId)){
			fail("优惠券id不能为null!");
			return;
		}
		ApiResponse apiResponse = UserService.dao.receiveCoupon(couponId , authUser);
		renderJson(apiResponse);
	}

	/**
	 * 获取所有领取的优惠券
	 * /xapp/user/userCouponList page size
	 */
	public void userCouponList(){
		String state = getPara("state");
		String type = getPara("type");
		Page<Coupon> couponPage = CouponService.dao.findAllListByUserId(getPageIndex() , getPageSize() , getAuthUser(),state,type);
		renderJson(couponPage);
	}


	/**
	 * 提交反馈意见
	 */
	public void feedback(){
		Feedback feedback = getModel(Feedback.class , "feedback");
		if(feedback.getId()==null){
			feedback.setCreateTime(new Date());
			feedback.setUserId(getAuthUserId().toString());
			boolean save = feedback.save();
			renderJson(new ApiResponse(save,save?"提交成功!":"提交失败!"));
		}else{
			boolean update = feedback.update();
			renderJson(new ApiResponse(update,update?"更新成功!":"更新失败!"));
		}
	}


	/**
	 * 获取自己提交的所有反馈
	 */
	public void feedbackList(){
		Page<Feedback> feedbackPage = Feedback.dao.feedbackList(getPageIndex() , getPageSize() , getAuthUser());
		renderJson(feedbackPage);
	}


	/**
	 * 绑定用户电话
	 */
	public void bindingPhone(){
		String phone = getPara("phone");
		String code = getPara("code");
		if(StringUtil.isBlank(phone)){
			fail("电话号码不能为null!");
			return;
		}
		if(StringUtil.isBlank(code)){
			fail("验证码不能为null!");
			return;
		}
		Boolean checkCode = MessageUtils.CheckCode(phone,code,MessageUtils.loginId);
		if(!checkCode){
			fail("验证码错误!");
			return;
		}
		WeixinUser user = WeixinUser.dao.findByPhoneNumber(phone);
		if(user!=null){
			fail("该手机号已被注册!");
			return;
		}
		WeixinUser authUser = getAuthUser();
		authUser.setUsername(phone);
		authUser.setMobile(phone);
		authUser.setBindPhone(phone);
		boolean update = authUser.update();
		if(update){
			WeixinUser.dao.cache_ClearByUserId(authUser.getId());
			CacheUtils.del(WeiXinRedisKey.getWeiXinUserByOpenid+authUser.getOpenid());
		}
		renderJson(new ApiResponse(update,update?"提交成功!":"提交失败!"));

	}

	/**
	 * 获取积分明细
	 */
	public void integralList(){
		WeixinUser authUser = getAuthUser();
		if(authUser==null){
			fail("用户未登录!");
			return;
		}
		Page<UserIntegralRecord> integralList = UserService.dao.findIntegralList(getPageIndex() , getPageSize() , authUser);
		renderJson(integralList);
	}


	/**
	 * 修改用户明细
	 */
	public  void  updateUserInfo(){
		String headImg = getPara("head_img");
		String nickName = getPara("nick_name");
		String birthday = getPara("birthday");
		WeixinUser authUser = getAuthUser();
		authUser.setHeadimgurl(headImg);
		authUser.setNickname(nickName);
		authUser.setBirthday(birthday);
		boolean update = authUser.update();
		if(update){
			WeixinUser.dao.cache_ClearByUserId(authUser.getId());
			CacheUtils.del(WeiXinRedisKey.getWeiXinUserByOpenid+authUser.getOpenid());
		}
		renderJson(new ApiResponse(update,update?"修改成功!":"修改失败!"));
	}

	/**
	 * 可用优惠券
	 */
	public void availableCoupon(){
		WeixinUser authUser = getAuthUser();
		if(authUser==null){
			fail("用户未登录!");
		}
		String productIds = getPara("product_ids");
		ApiResponse availableCouponList = UserCouponService.dao.findAvailableCouponList(productIds , authUser);
		renderJson(availableCouponList);
	}

	/**
	 * 评论回复列表
	 */
	public void commentReply(){
		WeixinUser authUser = getAuthUser();
		if(authUser==null){
			fail("用户未登录!");
			return;
		}
		Page<NoticeNewsCommentReply> notReadReply = NoticeNewsCommentReply.dao.findNotReadReply(getPageIndex() , getPageSize() , authUser);
		List<NoticeNewsCommentReply> list = notReadReply.getList();
		for (NoticeNewsCommentReply noticeNewsCommentReply : list) {
			noticeNewsCommentReply.put("time",OtherUtil.processingTime(noticeNewsCommentReply.getCreateTime(),"MM-dd HH:mm"));
		}
		Long replyNotReadNumber = NoticeNewsCommentReply.dao.countReplyNotReadNumber(authUser);
		Map<String,Object> map = new HashMap<>();
		map.put("count",replyNotReadNumber);
		map.put("page",notReadReply);
		renderJson(map);
	}

	/**
	 *	点击回复变成已读状态
	 */
	public void commentRead(){
		String replyId = getPara("reply_id");
		ApiResponse apiResponse = NoticeNewsService.dao.commentRead(replyId);
		renderJson(apiResponse);
	}

	/**
	 * 设置默认收货地址
	 * /xapp/user/changeDefaultAdd
	 */
	public void changeDefaultAdd(){
		String addressId = getPara("address_id");
		ApiResponse apiResponse = UserService.dao.changeDefaultAdd(addressId);
		renderJson(apiResponse);
	}

	/**
	 * 给用户添加推广的代理商
	 * /xapp/user/extension
	 */
	public void extension(){
		WeixinUser authUser = getAuthUser();
		if(authUser==null){
			fail("当前用户未登录！");
			return;
		}
		if(authUser.getExtensionId()!=null){
			fail("代理商已经绑定!");
			return;
		}
		Integer agentId = getParaToInt();
		if(agentId==null){
			fail("代理商id不能为空!");
			return;
		}
		authUser.setExtensionId(agentId);
		boolean update = authUser.update();
		renderJson(new ApiResponse(update,update?"更新成功!":"更新失败"));
	}

	/**
	 * 保存用户分享过来的用户
	 * /xapp/user/extension/extensionByUser
	 */
	public void extensionByUser(){
		String phone = getPara("phone");
		String code = getPara("code");
		if(StringUtil.isBlank(phone)){
			fail("电话号码不能为null!");
			return;
		}
		if(phone.length()!=11){
			fail("电话号码长度错误!");
			return;
		}
		if(StringUtil.isBlank(code)){
			fail("验证码不能为空!");
			return;
		}
		WeixinUser weixinUser = WeixinUser.dao.findbyBindPhone(phone);
		if(weixinUser!=null&&weixinUser.getExtensionId()!=null){
			fail("您已经注册过了!请直接登录小程序或APP");
			return;
		}
		boolean checkCode = MessageUtils.CheckCode(phone, code,MessageUtils.loginId);
		if(!checkCode){
			fail("验证码错误!");
			return;
		}
		MessageUtils.delCode(phone,MessageUtils.loginId);
		WeixinUser authUser = getAuthUser();
//		Integer agentId = getParaToInt("agent_id");
//		if(agentId==null){
//			fail("代理商id不能为null!");
//			return;
//		}
		String parentUserId = getPara("parent_user_id");
		WeixinUser extensionUser = WeixinUser.dao.findById(parentUserId);
		Integer extensionLevel = 0;
		if(extensionUser!=null){
			extensionLevel = extensionUser.getExtensionLevel();
			if(extensionLevel==null){
				extensionLevel = 0;
			}
			authUser.setExtensionUserId(extensionUser.getId());
			authUser.setExtensionId(extensionUser.getExtensionId());
		}
		authUser.setExtensionLevel(extensionLevel+1);
		authUser.setBindPhone(phone);
		authUser.setMobile(phone);
		authUser.setUsername(phone);
		boolean update = authUser.update();
		renderJson(new ApiResponse(update,update?"绑定成功!":"绑定失败!",update?authUser:""));
	}

	/**
	 * 用户提现
	 * /xapp/user/withdrawal
	 *
	 */
	public void withdrawal(){
		WeixinUser authUser = getAuthUser();
		String price = getPara("price");
		ApiResponse withdrawal = UserService.dao.withdrawal(authUser,price);
		renderJson(withdrawal);
	}

	/**
	 * 用户获利提现列表
	 * /xapp/user/incomeExpensesList
	 */
	public void incomeExpensesList(){
		Integer state = getParaToInt("state");
		WeixinUser authUser = getAuthUser();
		Page<UserRebate> page = UserService.dao.findUserRebate(authUser, getPageIndex(), getPageSize(),state);
		authUser.put("page",page);
		renderJson(authUser);
	}


	/**
	 * 绑定用户
	 * /xapp/user/bindingUser
	 */
	public void bindingUser(){
		//邀请人
		Integer inviter = getParaToInt("inviter");
		if(inviter==null){
			fail("邀请人不能为空!");
			return;
		}
		//被邀请人
		Integer userId = getParaToInt("user_id");
		if(userId==null){
			fail("被邀请人不能为空!");
			return;
		}
		WeixinUser authUser = getAuthUser();
		if(!authUser.getId().equals(userId)){
			fail("不能帮别人绑定");
			return;
		}
		Integer extensionUserId = authUser.getExtensionUserId();
		if(extensionUserId!=null){
			fail("不能绑定多次!");
			return;
		}
		authUser.setExtensionUserId(inviter);
		boolean update = authUser.update();
		renderJson(new ApiResponse(update,update?"更新成功":"更新失败"));
	}
}
